package com.example.watchs.handler;

import com.example.watchs.common.LogUtil;
import com.example.watchs.config.FileMonitorConfig;
import com.example.watchs.methods.BaseMethod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.WatchEvent;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author ieb
 */
@Service
public class FileConversionHandler {

    private final FileMonitorConfig fileMonitorConfig;

    /**
     * 池化五个线程，用于处理转换的方法
     */
    private final ExecutorService conversionExecutor = Executors.newFixedThreadPool(5);

    @Autowired
    public FileConversionHandler(FileMonitorConfig fileMonitorConfig) {
        this.fileMonitorConfig = fileMonitorConfig;
    }

    /**
     * 提交给线程池进行文件处理
     */
    public void convertFile(String fileParentPath, Path filePath, WatchEvent.Kind<?> kind) {
        conversionExecutor.submit(() -> {
            /**
             * 找到 转换的规则
             */
            BaseMethod conversionMethod = fileMonitorConfig.getConversionRules().get(Paths.get(fileParentPath));
            if (conversionMethod != null) {
                // 执行转换逻辑
                performConversion(filePath, conversionMethod, kind);
                // TODO 2025 08 11 13:28  记录转换信息到数据库
            } else {
                // TODO 2025 08 11 13:28   记录转换信息到数据库
               LogUtil.info(fileParentPath + "未找到相关处理方式");
            }
        });
    }

    /// 具体转换逻辑
    private void performConversion(Path filePath, BaseMethod conversionMethod, WatchEvent.Kind<?> kind) {
        try {
            boolean toConvert = conversionMethod.toConvert(filePath, kind);
            // TODO 2025 08 11 13:27   记录信息
            LogUtil.info(filePath + (toConvert ? "转换完成" : "转换失败"));
        } catch (Exception e) {
            // TODO 2025 08 11 13:27   记录报错信息
            LogUtil.info(e.getMessage());
        }
    }
}